#include "opencv2/opencv.hpp"	
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
//port of ColorSelect.py to c++ with added isCamera()
//tried to fix memory leak
using namespace cv;

bool isCamera(CvCapture* in);

int main(int argc, char** argv)
{
	std::cout << "Test stuff \n\n\n\n\n";
	int camera_index=0;
	//CvCapture* capture=cvCaptureFromCAM(camera_index);
	VideoCapture cap(0);	

	Scalar upper(18,255,255),lower(9,200,200);
	Mat mat1;
	namedWindow("Img", 1);
	namedWindow("HSV", 1);
	namedWindow("Binary", 1);	
	namedWindow("Contoured", 1);
	while(true)
	{
		//std::cout << "Test stuff \n\n\n\n\n";
		cap >> mat1;
		
		std::vector<std::vector<cv::Point> > contours;
		Mat hsv(mat1.size(),mat1.type());
		Mat binary(mat1.size(),CV_8UC1);
		Mat binary2(mat1.size(),CV_8UC1);
		cvtColor(mat1,hsv,CV_BGR2HSV);
		
		Mat hsv2(hsv.size(),hsv.type());
		bilateralFilter(hsv, hsv2, 5, 50, 50);
		inRange(hsv,lower,upper,binary);
		bilateralFilter(binary, binary2, 5, 50, 50);
		//std::cout << "Test stuff \n\n\n\n\n";
		Mat contourOut(binary2.clone());
		findContours(contourOut, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
		


		//Mat contourImage(binary2.size(), CV_8UC3, cv::Scalar(0,0,0));
		//std::cout << "Test stuff 3 \n\n\n\n\n";
    	std::vector<vector<Point> >::iterator contour=contours.begin();
		std::vector<Point> largest;
		int area=0;
		int max=area;
		//std::cout << "Test stuff 4 \n\n\n\n\n";
		for(;contour!=contours.end();++contour){
			std::cout << "Test stuff 5 \n\n\n\n\n";
			area=contourArea(*contour);
			if(area>max){
				max=area;
				largest=*contour;
			}
		}
		vector<vector<Point> > cl;
		cl.insert(cl.begin(),largest);
		if(!cl.empty()){
			//std::cout << "Test stuff 6 \n\n\n\n\n";
			drawContours(mat1,cl,0,Scalar(255,0,0),5);
			//std::cout << "Test stuff 7 \n\n\n\n\n";
		}
		//imshow("Contoured", contourImage);
		imshow("Img", mat1);
		imshow("HSV", hsv);
		imshow("Binary", binary);
		cvWaitKey(10);
		
	}
	
	return 0;
}

